'''
从 通用中下拉 模型
输入： 化学成份
输出： 模型
'''
from .config import *

from .log import train_log_config
LOGGER = train_log_config()
def conver_float_to_str(dictionary):
    """
    将字典中的所有嵌套值转换为str
    """
    result_dict = {}
    for key, value in dictionary.items():
        if isinstance(value, dict):
            # 递归调用以处理嵌套字典
            result_dict[key] = conver_float_to_str(value)
        elif isinstance(value, float) or isinstance(value, int):
            # 如果值是字符串且能被转换为float，则转换
            result_dict[key] = str(value)
        else:
            # 其他情况保持原样
            result_dict[key] = value

    return result_dict

data_input = {
    "modelCode": "cement_batching_general_model",
    "params": {
        "cement_type": "po425",
        "细度45μm": {

        },
        "比表": {

        },
        "SO3": {

        },
        "石灰石":
            {
                "工厂名": "玉山",
                "CaO": '40.1',
                "Loss": "30.2",
                "水份": '20.3',
                "SO3": '18.7',
            }
    }
}

#{'熟料': {'Loss': 0.64, 'CaO': 65.38, 'SO3': 0.47, '水份': 0.0}, '石灰石': {'Loss': 43.5, 'CaO': 39.0, 'SO3': 0.0, '水份': 1.0}, '建筑垃圾': {'Loss': 3.14, 'CaO': 2.8, 'SO3': 0.25, '水份': 1.98}, '水渣': {'Loss': -0.99, 'CaO': 38.89, 'SO3': 0.31, '水份': 9.28}, '石膏': {'Loss': 10.75, 'CaO': 30.95, 'SO3': 47.849999999999994, '水份': 5.6499999999999995}}


data_output = {
    "status": "success",
    "errorCode": 0,
    "errorMsg": "",
    "data": {
        "modelCode": "cement_batching_general_model",
        "modelCoef": {
            "石灰石": {
                "3d": -0.1,
                "28d": -0.8
            },
            "粉煤灰": {
                "3d": -0.2,
                "28d": -0.76
            }
        }
    }
}

def replace_H2O(data):
    for key, value in data.items():
        if isinstance(value, dict):
            replace_H2O(value)
        if '水份' in value:
            value['H2O'] = value.pop('水份')
    return data

def getModelFromGeneral(chemical_dict):
    import requests
    import os
    # if '$' in test_flag:
    #     url = basis_config["host_get_static"]
    # else:
    #     url = basis_config["host_get"]

    #本地环境,windows
    if os.name == "nt":
        LOGGER.info("*****本地环境获取url******")
        url = basis_config["host_get_static"]
    # k8s
    elif 'KUBERNETES_SERVICE_HOST' in os.environ:
        LOGGER.info("*****k8s环境获取url******")
        url = basis_config["host_get_for_service"]
    # zip包环境
    else:
        url = basis_config["host_get"]
        LOGGER.info("*****模型平台（需要替换）环境获取url, url = %s ******", url)

    chemical_dict = conver_float_to_str(chemical_dict)
    chemical_dict.pop("熟料","default_value")
    chemical_dict.pop("石膏","default_value")

    # chemical_dict = {material: {**properties, '工厂': '玉山'} for material, properties in chemical_dict.items()}
    data_input= {'modelCode': 'cement_batching_general_model', 'params': {}}
    data_input["params"]["cement_type"] = "po425"
    data_input["params"]["细度45μm"] = {}
    data_input["params"]["比表"] = {}
    data_input["params"]["SO3"] = {}
    data_input["params"]["截距"] = {}
    data_input["params"].update(chemical_dict)


    replace_H2O(data_input)
    print("data_input:",data_input)
    data_output = requests.post(url, json=data_input).json()
    print("data_output['data']", data_output["data"])
    if data_output["status"] == "success":
        model_coef = data_output["data"]
    else:
        raise ValueError(f"调用通用模型失败,输入{data_input}, 输出{data_output}")
    params_3d = {material: properties["coef_3d"] for material, properties in model_coef.items()}
    params_28d = {material: properties["coef_28d"] for material, properties in model_coef.items()}
    print(params_3d, params_28d)
    return params_3d, params_28d
